package com.qishon.pc.domain.service;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by yongwei.chen on 2017/1/4.
 */
@Component
@Slf4j
@RabbitListener(queues = "compressReceiver")
public class CompressReceiverService {
    @Value("${run.path}")
    private String filePath;

    @Value("${compress.tools.path}")
    private String cpTools;

    @Value("${firefox.config.filePath}")
    private String fireFoxPath;

    @Value("${compress.step.type}")
    private String compressType;

    @Value("${image.Types}")
    private  String imageTypes;

    @Autowired
    ProgressStepsService progressStepsSerivce;
    @RabbitHandler
    public void process(String msg) {
        log.info("compressReceiver:" + msg);
        System.out.println("compressReceiver 当前时间:"+ new Date());
        String[] str=msg.split(",");
        //款号
        String modelName=str[2];
        try {
            command(modelName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void copyFilesFromJoint(){

    }


    /**
     * 遍历文件，并将文件路径存到List中
     * @return
     * @throws IOException
     */
    public  void getFileName(String modelName,List<String> list) throws IOException {
        //所要遍历的文件夹
        String path= filePath +"\\"+"04.Joint\\"+modelName;
        File file=new File(path);
        //文件夹下的所有文件
        File [] files=file.listFiles();
        //List<String> list=new ArrayList();
        if (files != null){
            for(File f:files){
                if(f.isDirectory()){
                    getFileName(modelName+"\\"+f.getName(),list);
                }else {
                    if (f.getCanonicalPath().indexOf("Thumbs.db") == -1){
                        list.add(f.getCanonicalPath());
                    }
                }
            }
        }
//        return list;
    }

    /**
     * 压缩命令，并执行命令
     * @param
     * @throws IOException
     */
    public  void command(String modelName) throws IOException {
        List<String> listJoint = new ArrayList<String>();
        getFileName(modelName, listJoint);
        List<String> listCsv=readCsv(modelName);
        log.info("listJoint:" + listJoint);
        log.info("listCsv:" + listCsv);
        String s1=cpTools;
        String s2;
        String s3;
        String s4;
        String s5;
        String ones;
        String twos;
        String ss="";
        String s6=fireFoxPath;
        String bat;
        String[]  imagestr = imageTypes.split(",");
//        Runtime runtime=Runtime.getRuntime();
//        String test="D:\\CloudRender\\04.Joint\\J17002\\S5004001\\SKU_Full.png";
        for(int i=0;i<listJoint.size();i++){
            String str=listJoint.get(i);
            String[] s=str.split("\\\\");
            s2=s[0]+"\\\\"+s[1]+"\\\\"+s[2]+"\\\\"+s[3]+"\\\\"+s[4]+"\\\\"+s[5];//s[4]=S5004001;
            twos = s[0]+"\\\\"+s[1]+"\\\\"+s[2]+"\\\\"+s[3]+"\\\\"+s[4]+"\\\\";
            ones = s[0]+"\\"+s[1]+"\\"+s[2]+"\\"+s[3]+"\\"+s[4]+"\\";
            s3=str;
            int a=compare(s[4],listCsv);
//            String renameTemp1,renameTemp2;
            log.info("a = " + a);
            //s4的s[4]部分
            if(a!=-1 ){
                s[4]="PART\\\\"+(listCsv.get(a).split(","))[15]+"\\\\"+(listCsv.get(a).split(","))[19]+"\\\\"+(listCsv.get(a).split(","))[23];
                //s5的s[4]部分
                ss="PART\\"+(listCsv.get(a).split(","))[15]+"\\"+(listCsv.get(a).split(","))[19]+"\\"+(listCsv.get(a).split(","))[23];
                //图片名字
                s[5]=(listCsv.get(a).split(","))[27];
                // s[4] = "部件组编号"\"部件编号"\"面料或颜色编号"
                s4=filePath.replace("\\","\\\\") +"\\\\"+"05.Compress\\\\"+s[3]+"\\\\"+s[4];
                String name2 = twos + s[5].substring(0,s[5].indexOf("Full")) + s2.substring(s2.indexOf("Full"));
                boolean flag = rename(s2,name2);
                String newName = name2.split("\\\\")[name2.split("\\\\").length-1];
                log.info("newName = "+newName);
                if (!flag){
                    log.info("Renamed failed");
                }
                String oldFileName = listJoint.get(i).split("\\\\")[listJoint.get(i).split("\\\\").length-1];
                // s[5] = "图片地址"，其中的 "Full" 改成图片的序号-1
                s5=filePath +"\\"+"05.Compress\\"+s[3]+"\\"+ss+"\\"+newName;
                System.out.println("这是S4："+s4);
                System.out.println("这是S5："+s5);
                s3 = ones + newName;
                bat="cmd /c "+s1+" "+s2+" "+ s3+" "+s4+" "+s5+" "+s6;
                log.info("implement program: "+bat);
                if (compressType.toUpperCase().equals("COPY")){
                    boolean result = false;
                    //目标地址
                    String src = twos +"\\"+ newName;
                    //目的地址
                    String des = s4+"\\"+newName;
                    //拷贝文件
                    result = progressStepsSerivce.copy(src,des,true);
                    if (!result){
                        log.info("Copy files failed !");
                    }
                }else {
                    String commons[] = {s1,s3,s3,s4,s5,s6};
                    Process child = Runtime.getRuntime().exec(commons);
                    BufferedReader buf = new BufferedReader(new InputStreamReader(child.getErrorStream()));
                    String str2 = "";
                    while((str2 = buf.readLine())!= null)
                    {
                        log.info(str2);
                    }
                }
            }else {
                log.info("The part code is not right !");
            }
        }
    }

    /**
     * 读取csv文件
     * @throws IOException
     */
    public  List<String> readCsv(String modelName) throws IOException {
        File file=new File(filePath +"\\"+"01.Model\\"+modelName);
        List<String> list=new ArrayList<>();
        File[] files=file.listFiles();
        for(File f:files){
            if(f.getName().endsWith("_02.csv")){
                BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(f.getCanonicalFile())));
                String line;
                while ((line=br.readLine())!=null){
                    //将csv文件每一行数据添加到list中；
                    list.add(line);
                }
                return list;
                //System.out.println(list1.get(1));
            }
        }
        return list;
    }

    /**
     *
     * @param s 文件夹名
     * @param list csv文件
     * @return
     */
    public static int compare(String s,List<String> list){
        for(int i=0;i<list.size();i++){
            String[] s1=list.get(i).split(",");
            log.info("s = "+ s);
            log.info("s1[19] = "+s1[19]);
            if(s.equals(s1[19])){
                int a=i;
                return a;
            }
        }
        return -1;
    }
    /**
     * 文件重命名的方法
     */
    public static boolean rename(String oldname,String newname){
        File old = new File(oldname);
        log.info("oldname:"+oldname);
        File renew = new File(newname);
        log.info("newname:"+newname);
        boolean flag = old.renameTo(renew);
        log.info("rename result:"+flag);
        return flag;
    }
}
